package com.zmxstudy.rbac.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.zmxstudy.rbac.entity.Role;
import com.zmxstudy.rbac.entity.UserAndRole;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author star
 * @description 针对表【role(角色表)】的数据库操作Mapper
 * @createDate 2024-04-03 15:37:14
 * @Entity com.zmxstudy.rbac.entity.Role
 */
@Component
public interface RoleMapper extends BaseMapper<Role> {
    @Delete("DELETE FROM role_auth WHERE role_id=#{roleId}")
    boolean deleteAuthsByRoleId(@Param("roleId") Long roleId);

    @Insert("<script>" +
            "INSERT INTO role_auth(role_id,auth_id) VALUES " +
            "<foreach collection='authIds' item='item' separator=','>" +
            "   (#{roleId}, #{item})" +
            "</foreach>" +
            "</script>")
    boolean insertRolesBatch(@Param("roleId") Long roleId, @Param("authIds") List<Long> authIds);

    /**
     * 查询所有用户的用户名和角色
     */
//
    @Select("SELECT user_role.user_id,user_role.role_id,username,rolename from user JOIN user_role on user.id=user_role.user_id JOIN role on user_role.role_id=role.id")
    List<UserAndRole> listAllUserAndRole();


    @Select("SELECT user_role.user_id,user_role.role_id,username,rolename from user JOIN user_role on user.id=user_role.user_id JOIN role on user_role.role_id=role.id where username  like #{username} ")
    List<UserAndRole> listUserAndRoleByUsername(@Param("username") String username);

    @Delete("delete from user_role where user_id = #{userId} and role_id = #{roleId}" )
    boolean delUserAndRole(@Param("userId") int userId,@Param("roleId") int roleId);


    @Insert("INSERT INTO user_role VALUES (#{userId}, #{roleId})")
    boolean plusRoles(@Param("userId") int userId, @Param("roleId") int roleId);


    @Select("select user_role.role_id from user_role where user_id = #{userId}")
    List<Long> findRoleIds(@Param("userId")  Long userId);

//    @Insert("<script>" +
//            "INSERT INTO user_role  VALUES " +
//
//            "   (#{userId}, #{item},#{creatBy})"  +
//
//            "</script>")
//    boolean plusRoles(@Param("userId") Long userId, @Param("roleId") Long roleId,@Param("creatBy") String creatBy);

}




